<template>
    <div class="page">
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="4">
                                    <h5>会员管理</h5>
                                </el-col>
                                <el-col :offset="5" :span="3">
                                    <el-button size="medium" type="warning" style="background: rgba(248,154,55,1);" @click="openCreateDialog()">新增</el-button>
                                </el-col>
                                <el-col :span="6">
                                    <el-date-picker size="medium" v-model="queryParams.created_at" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                                    </el-date-picker>
                                </el-col>
                                <el-col :span="6">
                                    <el-input size="medium" placeholder="请输入搜索条件" v-model="queryParams.name">
                                        <el-button size="medium" slot="append"  icon="el-icon-search" @click="search()"></el-button>
                                    </el-input>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                <div class="panel">
                    <div class="panel-body">
                        <el-row :gutter="20">
                            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                                <el-table :data="memberData.data" style="width: 100%" v-loading="listLoading" @row-click="rowClick">
                                    <el-table-column
                                        prop="name"
                                        label="会员姓名">
                                    </el-table-column>
                                    <el-table-column
                                        prop="phone"
                                        label="手机号码">
                                    </el-table-column>
                                    <el-table-column
                                        prop="service_name"
                                        label="关联站点">
                                    </el-table-column>
                                    <el-table-column
                                        prop="created_at"
                                        label="注册时间">
                                    </el-table-column>
                                    <el-table-column
                                        label="配送方式">
                                        <template slot-scope="scope">{{ scope.row.send_type === '0' ? "自提" : "派送" }}</template>
                                    </el-table-column>
                                    <!--<el-table-column
                                        prop="appointment_time"
                                        label="预约送达时间">
                                    </el-table-column>
                                    <el-table-column
                                        prop="company_address"
                                        label="公司">
                                    </el-table-column>-->
                                </el-table>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="panel-footer text-right">
                        <el-pagination @size-change="sizeChange" @current-change="currentChange"
                                       :current-page="queryParams.page"
                                       :page-sizes="[5, 10, 20, 50]"
                                       :page-size="queryParams.paginate"
                                       layout="total, sizes, prev, pager, next, jumper"
                                       :total="memberData.total">
                        </el-pagination>
                    </div>
                </div>
            </div>
            </el-col>
        </el-row>
        <!--新增会员对话框-->
        <el-dialog title="新增会员" :visible.sync="createDialog" width="30%" :before-close="handleCreateClose">
            <el-form ref="addForm" :rules="createRule" :model="createParams" label-width="80px">
                <el-form-item label="用户姓名" prop="name">
                    <el-input size="medium" v-model="createParams.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input size="medium" v-model="createParams.phone" maxlength="11"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="medium" @click="handleCreateClose">取 消</el-button>
                <el-button size="medium" type="warning" style="background: rgba(248,154,55,1);" @click="createMember()">确 定</el-button>
            </span>
        </el-dialog>
        <!--编辑会员对话框-->
        <el-dialog :visible.sync="editDialog" width="32%" :before-close="handleEditClose">
            <span slot="title" class="dialog-header">
                <el-row>
                    <el-col :span="10">
                        <p style="font-size: 24px;">{{editData.name}}</p>
                    </el-col>
                    <el-col :span="14">
                        <el-row v-if="editing">
                            <el-col :span="8" :offset="4" v-if="editBtn"><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="editQuery">保存</el-button></el-col>
                            <el-col :span="8" v-if="editBtn"><el-button type="danger" size="medium" @click="delQuery">删除</el-button></el-col>
                        </el-row>
                        <el-row v-else>
                            <el-col :span="8" :offset="4" v-if="editBtn"><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="enableEdit">编辑</el-button></el-col>
                            <el-col :span="8" v-if="editBtn"><el-button size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                        </el-row>
                    </el-col>
                </el-row>
                <el-row>
                    <el-tabs v-model="tabName" @tab-click="tabClick">
                        <el-tab-pane label="会员信息" name="info">
                            <el-form ref="editForm" :rules="editRule" :model="editParams" label-width="120px">
                                <el-form-item label="会员姓名：" prop="name">
                                    <el-input v-model="editParams.name" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="手机号码：" prop="phone">
                                    <el-input v-model="editParams.phone" :disabled="!editing" maxlength="11"></el-input>
                                </el-form-item>
                                <el-form-item label="注册时间：">
                                    <p>{{editData.created_at}}</p>
                                </el-form-item>
                                <el-form-item label="注册方式：">
                                    <p>{{editData.reg_type == 0?'微信':'后台'}}</p>
                                </el-form-item>
                                <el-form-item label="配送方式：">
                                    <p>{{editData.send_type == 0?'自提':'配送'}}</p>
                                </el-form-item>
                                <el-form-item label="派送件：">
                                    <p>{{editData.ps_num}}</p>
                                </el-form-item>
                                <el-form-item label="自提件：">
                                    <p>{{editData.zt_num}}</p>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="操作日志" name="log">
                            <el-table :data="logData.data" style="width: 100%" >
                                <el-table-column prop="created_at">
                                </el-table-column>
                                <el-table-column >
                                    <template slot-scope="scope">
                                        <el-row>
                                            {{scope.row.name}}{{scope.row.operation}}
                                        </el-row>
                                        <el-row v-if="scope.row.history!=null&&scope.row.actuality!=null">
                                            <p>修改前：<br><span v-for="(item,index) in scope.row.history">{{index}}:{{item}}<br></span></p>
                                            <p>修改后：<br><span v-for="(item,index) in scope.row.actuality">{{index}}:{{item}}<br></span></p>
                                        </el-row>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination @size-change="logSizeChange" @current-change="logCurrentChange"
                                           :current-page="queryLogParams.page"
                                           :page-sizes="[5,10, 20, 50]"
                                           :page-size="queryLogParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="logData.total">
                            </el-pagination>
                        </el-tab-pane>
                    </el-tabs>
                </el-row>
            </span>
        </el-dialog>
    </div>

</template>

<script>
    import api from '../apis'
    import Vue from 'vue';
    import store from '../store'
    export default {
        name: "Member",
        data (){
            let checkMobile = (rule, value, callback) => {
                let phone=/^[1][3,4,5,7,8][0-9]{9}$/;
                if (!phone.test(value)) {
                    callback(new Error('请输入正确的手机号'));
                } else {
                    callback();
                }
            };
            return {
                //列表加载开关
                listLoading:false,
                //新增对话框开关
                createDialog:false,
                //编辑对话框开关
                editDialog:false,
                //编辑对话框按钮显示隐藏状态
                editBtn:true,
                //是否开启修改
                editing:false,
                //编辑对话框默认标签页
                tabName: 'info',
                //会员列表数据
                memberData:{
                    data: [],
                    total: 0,
                },
                //日志数据
                logData:{
                    data:[],
                    total:0,
                },
                //日志请求参数
                queryLogParams:{
                    page:1,
                    paginate:5,
                    type:1,
                    uid:'',
                },
                //列表请求参数
                queryParams: {
                    page: 1,
                    paginate: 10,
                    name:'',
                    created_at:'',
                },
                //新增请求参数
                createParams:{
                    phone:'',
                    name:'',
                },
                //新增验证规则
                createRule:{
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'},
                    ],
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ]
                },
                //修改请求参数
                editParams:{
                    phone:'',
                    name:'',
                },
                //修改验证规则
                editRule:{
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ]
                },
                //修改对话框数据
                editData:{
                    user_log:{
                        data:[],
                    }
                },
            }
        },
        methods:{
            /**
             * 请求会员列表
             */
            queryMember() {
                this.listLoading = true;
                api.member.fetch(this.queryParams).then(response => {
                    this.memberData = response.data;
                    this.listLoading = false;
                }).catch(errors => {

                });
            },
            /**
             * 根据id获取详情
             */
            fetchById(id,params){
                api.member.fetchById(id,params).then(response=>{
                    this.editData = {...response.data.data};
                    this.editParams.name = response.data.data.name;
                    this.editParams.phone = response.data.data.phone;
                }).catch(errors=>{
                    this.$message.error(errors.response.data.resultMessage);
                });
            },
            /**
             * 新增会员请求
             */
            createMember(){
                this.$refs['addForm'].validate((valid) =>{
                    if(valid){
                        api.member.create(this.createParams).then(response=>{
                            this.jumpToLastPage();
                            this.handleCreateClose();
                            this.$message.success('新增成功');
                        }).catch(errors=>{
                            this.$message.error(errors.response.data.resultMessage);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             * 改变每页数量的时候请求列表
             * @param size
             */
            sizeChange(size){
                this.queryParams.paginate = size;
                this.queryMember();
            },
            /**
             * 日志列表每页数量的时候
             */
            logSizeChange(size){
                this.queryLogParams.paginate = size;
                this.fetchLogs();
            },
            /**
             * 改变当前页的时候请求列表
             * @param index
             */
            currentChange(index){
                this.queryParams.page = index;
                this.queryMember();
            },
            /**
             * 日志列表改变当前页的时候请求列表
             */
            logCurrentChange(index){
                this.queryLogParams.page = index;
                this.fetchLogs();
            },
            /**
             * 跳转到最后一页
             */
            jumpToLastPage () {
                let last = Math.ceil(this.memberData.total / this.queryParams.paginate);
                if (this.queryParams.page < last) {
                    this.queryParams.page = last;
                }
                this.queryMember();
            },
            /**
             * 搜索按钮请求列表
             */
            search(){
                this.queryMember();
            },
            /**
             * 打开新增对话框
             */
            openCreateDialog(){
                this.createDialog = true;
            },
            /**
             * 关闭新增对话框
             */
            handleCreateClose(){
                this.createParams = {
                    phone:'',
                    name:'',
                }
                this.createDialog = false;
                this.$refs['addForm'].resetFields();
            },
            /**
             * 关闭修改对话框
             */
            handleEditClose(){
                this.editDialog = false;
                this.editData = {
                    user_log:{
                        data:[],
                    }
                };
                this.editing = false;
                this.editBtn = true;
                this.tabName = 'info';
                this.$refs['editForm'].resetFields();
            },
            /**
             * 列表行选中
             * @param row
             * @param event
             * @param column
             */
            rowClick(row, event, column){
                this.queryLogParams.uid = row.id;
                this.fetchById(row.id);
                this.editDialog = true;
                this.fetchLogs();
            },
            /**
             * 编辑对话框标签页切换
             */
            tabClick(tab, event){
                if(tab.name=='info'){
                    this.editBtn = true;
                }else{
                    this.editBtn = false;
                }
            },
            /**
             * 修改对话框点击修改按钮
             */
            enableEdit(){
                this.editing = true;
            },
            /**
             * 修改对话框点击删除按钮
             */
            delQuery(){
                this.$confirm('确认删除用户？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    api.member.destroy(this.editData.id).then(response=>{
                        this.queryMember();
                    }).catch(errors=>{
                        this.$message.error(errors.response.data.resultMessage);
                    });
                }).catch(() => {

                });
            },
            /**
             * 修改对话框点击保存按钮
             */
            editQuery(){
                this.$refs['editForm'].validate((valid) =>{
                    if(valid){
                        api.member.update(this.editData.id,this.editParams).then(response=>{
                            for (let i in this.memberData.data){
                                if(this.memberData.data[i].id==this.editData.id){
                                    Vue.set(this.memberData.data, i, response.data.data);
                                    break;
                                }
                            }
                            this.handleEditClose();
                            this.$message.success('修改成功');
                        }).catch(errors=>{
                            this.$message.error(errors.response.data.resultMessage);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             * 操作日志请求
             */
            fetchLogs()
            {
                api.log.fetch(this.queryLogParams).then(response=>{
                    this.logData = response.data;
                    for(let i in this.logData.data){
                        if(this.logData.data[i].actuality!=null){
                            this.logData.data[i].actuality = JSON.parse(this.logData.data[i].actuality);
                        }
                        if(this.logData.data[i].history!=null){
                            this.logData.data[i].history = JSON.parse(this.logData.data[i].history);
                        }
                    }
                }).catch(errors=>{
                    this.$message.error('请求失败，'+response.data.resultCode);
                })
            }
        },
        mounted (){
            this.queryMember();
        }
    }
</script>

<style lang="scss" scoped>
    /* 日历插件样式 */
    .el-date-editor--daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner {
        width: 100%;
    }
    .el-range-editor.is-active, .el-range-editor.is-active:hover {
        border-color: #e6a23c;
    }
    /* 模拟框中的form item */
    .el-form-item {
        margin-bottom: 0px;
    }
    .el-form-item__content {
        line-height: 30px;
    }
</style>
<style lang="scss">
    .el-date-table td.available:hover {
        color: #e6a23c;
    }
    .el-date-table td.today span {
        color: #e6a23c;
    }
    .el-date-table td.end-date span, .el-date-table td.start-date span,
    .el-date-table td.end-date span, .el-date-table td.start-date span {
        background-color: #e6a23c;
    }
    /* 搜索框样式 */
    .el-input.is-active .el-input__inner, .el-input__inner:focus {
        border-color: #e6a23c;
    }
</style>
